package cn.gavin.web.controller;

import cn.gavin.domain.Employee;
import cn.gavin.qo.JsonResult;
import cn.gavin.service.IEmployeeService;
import cn.gavin.service.IPermissionService;
import cn.gavin.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/userLogin")
    @ResponseBody
    public JsonResult login(String username, String password, HttpSession session){
        Employee employee = employeeService.login(username,password);
        // 把用户信息存到 session
//            session.setAttribute(UserContext.USER_IN_SESSION,employee);
        UserContext.setUserInSession(employee); // 优化之后
        if (!employee.isAdmin()){ // 把权限信息存到 session
            List<String> stringList = permissionService.selectByEmpId(employee.getId());
//                session.setAttribute(UserContext.PERMISSION_IN_SESSION,stringList);
            UserContext.setPermissions(stringList); // 优化之后
        }
        return new JsonResult();
    }

    @RequestMapping("/userLogout")
    public String logout(HttpSession session){
        // 销毁 session 会话
        session.invalidate();
        return "redirect:/login.html";
    }

    @RequestMapping("/nopermission")
    public String nopermission(){
        return "common/nopermission";
    }
}
